import { mapMutations, mapActions, mapState } from "vuex";
import { typeClassName } from "@/pages/config/classNameMap";
import _ from "lodash";
const requireComponent = require.context("./", true, /[A-Z]\w+\.(vue)$/);
const comp = {};
requireComponent.keys().forEach((fileName) => {
  if (fileName != "./index.vue") {
    const componentConfig = requireComponent(fileName);
    const name = componentConfig.default.name;
    const componentName = _.camelCase(
      name
        .split("/")
        .pop()
        .replace(/\.\w+$/, "")
    );
    comp[componentName] = componentConfig.default || componentConfig;
  }
});
Object.keys(comp).map((key) => {
  comp[key].components = comp;
});
export default {
  components: comp,
  data() {
    return {
      vms: {}, //页面组件vue实例
      completeLoad: false,
      me: this,
      watchs: [],
      //模型
      models: {
        //模型

        product: {
          ...typeClassName["product"],
        },
        productTtype: {
          ...typeClassName["productTtype"],
        },
        technologyParam: {
          ...typeClassName["technologyParam"],
        },
        equipment: {
          ...typeClassName["equipment"],
        },
      },
      tabsIndex: null,
      rowId: null,
      productTypeCodeOptions: [
        {
          label: "请选择",
          value: "请选择",
        },
      ],
      technologyParamOptions: [],
      equipmentOptions: [
        {
          label: "请选择",
          value: "请选择",
        },
      ],
      dataSet: {
        currentData: {},
        //数据集
        formData: {
          sf_code: "",
          sf_name: "",
        },
        tableData: [],
      },
    };
  },
  provide() {
    return {
      anc: this,
    };
  },
  computed: {},
  created() {
    Object.keys(this.models).map((k) => {
      this.models[k].clz = this.$modelObject.create(this.models[k].modelType);
      this.models[k].clzs = this.$modelObject.create(
        this.models[k].modelType + "Collection"
      );
    });
  
  },
  mounted() {
    this.watchs.map((item) => {
      this.$watch(item.target, item.fn, { deep: item.deep });
    });
    this.$nextTick(() => {
      console.log(comp, "comp");
      this.unwatch = this.$watch("vms", (newValue, oldValue) => {
        let flag = true;
        Object.keys(comp).map((k) => {
          if (!Object.keys(this.vms).includes(k)) {
            flag = false;
          }
        });
        this.completeLoad = flag;
      });
      this.init();
      if (process.env.NODE_ENV === "development") {
        console.log({
          me: this,
          vms: this.vms,
          completeLoad: this.completeLoad,
        });
      }
    });
  },
  destroyed() {
    this.unwatch();
  },
  methods: {
    init() {
      // this.getProductTtypeOptions();
      // this.getTechnologyParamOptions();
    },
    loadPage(pageNavigation, filter) {
      let newFilter = {
        ...filter,
        className: this.models.product.className,
        type: this.models.product.type,
      };
      this._$queryByPage(
        this.models["product"].clzs,
        pageNavigation,
        newFilter,
        "",
        "updateTime",
        false
      ).then((res) => {
        this.dataSet.tableData = this.models["product"].clzs.valueRecords;
      });
    },
    /**
     * 新增-弹窗显示
     */
    handleCreate() {
      this._modalShow("createModal");
      this.vms.createView.resetFields();
    },
    /**
     * 查看-弹窗显示
     * @param {*} row
     */
    handleDetail(row) {
      this._modalShow("detailModal");
      this.dataSet.currentData = row;
      this.dataSet.formData = {
        ...row.values,
      };
    },
    /**
     * 编辑-弹窗显示
     * @param {*} row
     */
    handleEdit(row) {
      this._modalShow("editModal");
      this.dataSet.currentData = row;
      // this.dataSet.formData = row;
      this.dataSet.formData = {
        ...row.values,
      };
    },

    /**
     * 删除单行
     * @param {行数据} row
     * @param {索引} index
     */
    handleDelete(row, index) {
      let _this = this;
      this.$api.inspection
        .isProductHasContent({
          id: row.id,
        })
        .then((flag) => {
          if (flag) {
            this._$deleteConfirm(() => {
              _this
                ._$deleteByIds(_this.models.product.clzs, [String(row.id)])
                .then((res) => {
                  _this.models["product"].clzs.records.splice(index, 1);
                  _this.dataSet.tableData =
                    _this.models["product"].clzs.setValueRecords();
                  _this.vms.mainTable.navigation.page.total--;
                });
            });
          } else {
            this.$Message.info("该产品有工艺参数或实验室参数，不能删除");
          }
        });
    },
    handleDeleteMultiple(selection) {
      let _this = this;
      this._$deleteConfirm(() => {
        let ids = selection.map((item) => String(item.id));
        _this._$deleteByIds(_this.models.product.clzs, ids).then((res) => {
          _this.vms.mainTable.navigation.page.pageNumber = 1;
          _this.loadPage(_this.vms.mainTable.navigation, {});
        });
      });
    },
    // 新增确认
    createModalOk(btn) {
      this._$validateAll([this.vms.createView], (valid) => {
        btn.loading = false;
        if (valid) {
          let formData = this.$modelObject.getTpl(
            this.models.product.modelType
          );
          formData.className = this.models.product.className;
          formData.type = this.models.product.type;
          formData.name = +new Date();
          formData.values = this.dataSet.formData;
          formData.values.productTypeName = this._$getOptionValue(
            this.productTypeCodeOptions,
            this.dataSet.formData.productTypeCode
          );

          formData.values.equipName = this._$getOptionValue(
            this.equipmentOptions,
            this.dataSet.formData.equipId
          );
          this._$add(this.models["product"].clz, formData).then((flag) => {
            if (flag) {
              this._modalClose("createModal");
              this.loadPage(this.vms.mainTable.navigation.page, {});
            }
          });
        } else {
          btn.loading = false;
          this.$Message.info("请填写必填内容");
        }
      });
      btn.loading = false;
    },
    // 编辑确认
    editModalOk(btn) {
      this.vms.editView.validate((valid) => {
        btn.loading = false;
        if (valid) {
          this.dataSet.formData.productTypeName = this._$getOptionValue(
            this.productTypeCodeOptions,
            this.dataSet.formData.productTypeCode
          );
          this.dataSet.formData.equipName = this._$getOptionValue(
            this.equipmentOptions,
            this.dataSet.formData.equipId
          );
          this.dataSet.currentData.values = {
            ...this.dataSet.formData,
          };
          this.models.product.clz.setRecord(this.dataSet.currentData);
          this.models.product.clz.updateById().then((flag) => {
            if (flag) {
              this._modalClose("editModal");
              this._resetForm("editView");
              this.loadPage(this.vms.mainTable.navigation.page, {});
            } else {
              this._modalClose("editModal");
            }
          });
        } else {
          btn.loading = false;
          this._$requireInfo();
        }
      });
      btn.loading = false;
    },
    /**
     * 切换状态
     */
    changeStatus(row) {
      console.log(row);
      let data = {
        id: row.id,
      };
      this.$Modal.confirm({
        title: "确认切换状态？",
        cancelText: "取消",
        onOk: () => {
          this.$api.inspection.start(data).then((flag) => {
            if (flag) {
              this.loadPage(this.vms.mainTable.navigation.page, {});
            }
          });
        },
        onCancel: () => {},
      });
    },
    getReturnTrue() {
      Promise.all([
        this.getProductTtypeOptions(),
        this.getEquipmentOptions(),
      ]).then((res) => {
        console.log(res);

        this.vms.createView.beforePageInit();
        this.vms.editView.beforePageInit();
        this.vms.detailView.beforePageInit();
      });
    },
    getProductTtypeOptions() {
      let data = {
        className: this.models.productTtype.className,
        type: this.models.productTtype.type,
      };
      this.productTypeCodeOptions = [];
      return this._$query(this.models.productTtype.clzs, data).then((flag) => {
        // console.log(this.models.productTtype.clzs);
        if (flag) {
          this.models.productTtype.clzs.records[0].hier.content.forEach((d) => {
            if (d.name !== "root") {
              this.productTypeCodeOptions.push({
                label: d.values.sf_name,
                value: String(d.id),
              });
            }
          });
          return true;
        } else {
          return false;
        }
      });
    },
    getEquipmentOptions() {
      let data = {
        className: this.models.equipment.className,
        type: this.models.equipment.type,
      };
      return this._$query(this.models.equipment.clzs, data).then((flag) => {
        console.log(this.models.equipment.clzs);
        if (flag) {
          this.equipmentOptions = [];
          this.models.equipment.clzs.records.forEach((d) => {
            this.equipmentOptions.push({
              label: d.values.sf_name,
              value: String(d.id),
            });
          });
          return true;
        } else {
          return false;
        }
      });
    },
  },
};
